package com.amu.aidemo.ui

import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.amu.aidemo.ui.model.AssistantState
import com.amu.aidemo.ui.model.ChatMessage
import com.amu.aidemo.ui.model.MessageType
import com.amu.aidemo.ui.model.VoiceAssistantUiState

@Composable
fun VoiceAssistantScreen(
    uiState: VoiceAssistantUiState = VoiceAssistantUiState(),
    onMicClick: () -> Unit = {},
    onStopAll: () -> Unit = {},
    onTestClick: () -> Unit = {},
    modifier: Modifier = Modifier
) {
    Box(
        modifier = modifier
            .fillMaxSize()
            .background(
                Brush.verticalGradient(
                    colors = listOf(
                        Color(0xFF1A1A2E),
                        Color(0xFF16213E)
                    )
                )
            )
    ) {
        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 顶部状态栏
            StatusBar(
                state = uiState.state,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            )

            // 消息列表
            MessageList(
                messages = uiState.messages,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
            )

            // 当前转录文本
            if (uiState.currentTranscript.isNotEmpty()) {
                TranscriptText(
                    text = uiState.currentTranscript,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 24.dp, vertical = 8.dp)
                )
            }

            // 波形动画和按钮区域
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 32.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 波形动画和麦克风按钮
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 24.dp),
                    contentAlignment = Alignment.Center
                ) {
                    // 波形动画
                    if (uiState.isAnimating) {
                        WaveformAnimation(
                            state = uiState.state,
                            modifier = Modifier.size(280.dp)
                        )
                    }

                    // 麦克风按钮
                    MicrophoneButton(
                        state = uiState.state,
                        onClick = onMicClick,
                        modifier = Modifier.size(80.dp)
                    )
                }
                
                // 按钮行
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 24.dp),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    // 测试按钮
                    if (uiState.state == AssistantState.IDLE) {
                        OutlinedButton(
                            onClick = onTestClick,
                            modifier = Modifier.weight(1f),
                            colors = ButtonDefaults.outlinedButtonColors(
                                contentColor = Color(0xFF00D9FF)
                            )
                        ) {
                            Icon(
                                imageVector = Icons.Filled.Settings,
                                contentDescription = "模块测试",
                                modifier = Modifier.size(20.dp)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text("模块测试")
                        }
                    }
                    
                    // 停止所有活动按钮
                    if (uiState.state != AssistantState.IDLE) {
                        Button(
                            onClick = onStopAll,
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFFDC3545)
                            ),
                            modifier = Modifier.weight(1f)
                        ) {
                            Icon(
                                imageVector = Icons.Filled.Close,
                                contentDescription = "停止",
                                modifier = Modifier.size(20.dp)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = "停止",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun StatusBar(
    state: AssistantState,
    modifier: Modifier = Modifier
) {
    val (statusText, statusColor) = when (state) {
        AssistantState.IDLE -> "待机中" to Color(0xFF6C757D)
        AssistantState.CONNECTING -> "连接中，请稍候..." to Color(0xFFFF9800)
        AssistantState.LISTENING -> "正在聆听..." to Color(0xFF4CAF50)
        AssistantState.THINKING -> "思考中..." to Color(0xFFFFC107)
        AssistantState.SPEAKING -> "回复中..." to Color(0xFF2196F3)
    }

    Row(
        modifier = modifier,
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Box(
            modifier = Modifier
                .size(8.dp)
                .clip(CircleShape)
                .background(statusColor)
        )
        Spacer(modifier = Modifier.width(8.dp))
        Text(
            text = statusText,
            color = Color.White,
            fontSize = 16.sp,
            fontWeight = FontWeight.Medium
        )
    }
}

@Composable
private fun MessageList(
    messages: List<ChatMessage>,
    modifier: Modifier = Modifier
) {
    val listState = rememberLazyListState()

    LaunchedEffect(messages.size) {
        if (messages.isNotEmpty()) {
            listState.animateScrollToItem(messages.size - 1)
        }
    }

    if (messages.isEmpty()) {
        Box(
            modifier = modifier,
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "你好！我是你的AI语音助手\n点击下方麦克风开始对话",
                color = Color.White.copy(alpha = 0.6f),
                fontSize = 16.sp,
                textAlign = TextAlign.Center,
                lineHeight = 24.sp
            )
        }
    } else {
        LazyColumn(
            modifier = modifier.padding(horizontal = 16.dp),
            state = listState,
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            items(messages, key = { it.id }) { message ->
                MessageBubble(message = message)
            }
        }
    }
}

@Composable
private fun MessageBubble(
    message: ChatMessage,
    modifier: Modifier = Modifier
) {
    val isUser = message.type == MessageType.USER
    val backgroundColor = if (isUser) Color(0xFF0084FF) else Color(0xFF2C2C3E)

    Row(
        modifier = modifier.fillMaxWidth(),
        horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start
    ) {
        Surface(
            modifier = Modifier.widthIn(max = 280.dp),
            shape = RoundedCornerShape(
                topStart = 20.dp,
                topEnd = 20.dp,
                bottomStart = if (isUser) 20.dp else 4.dp,
                bottomEnd = if (isUser) 4.dp else 20.dp
            ),
            color = backgroundColor
        ) {
            Column(
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)
            ) {
                // 消息内容
                Text(
                    text = message.content,
                    color = Color.White,
                    fontSize = 15.sp
                )
                
                // 耗时信息
                val timingInfo = buildTimingInfo(message, isUser)
                if (timingInfo.isNotEmpty()) {
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = timingInfo,
                        color = Color.White.copy(alpha = 0.6f),
                        fontSize = 11.sp,
                        lineHeight = 14.sp
                    )
                }
            }
        }
    }
}

private fun buildTimingInfo(message: ChatMessage, isUser: Boolean): String {
    val parts = mutableListOf<String>()
    
    if (isUser && message.asrDuration > 0) {
        parts.add("ASR: ${message.asrDuration}ms")
    }
    
    if (!isUser) {
        if (message.llmDuration > 0) {
            parts.add("LLM: ${message.llmDuration}ms")
        }
        if (message.ttsDuration > 0) {
            parts.add("TTS: ${message.ttsDuration}ms")
        }
    }
    
    return parts.joinToString(" | ")
}

@Composable
private fun TranscriptText(
    text: String,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier,
        shape = RoundedCornerShape(16.dp),
        color = Color(0xFF2C2C3E).copy(alpha = 0.8f)
    ) {
        Text(
            text = text,
            color = Color.White.copy(alpha = 0.9f),
            fontSize = 14.sp,
            modifier = Modifier.padding(16.dp),
            textAlign = TextAlign.Center
        )
    }
}

@Composable
private fun WaveformAnimation(
    state: AssistantState,
    modifier: Modifier = Modifier
) {
    val infiniteTransition = rememberInfiniteTransition()
    
    val animationDuration = when (state) {
        AssistantState.CONNECTING -> 1200
        AssistantState.LISTENING -> 1000
        AssistantState.THINKING -> 1500
        AssistantState.SPEAKING -> 800
        else -> 1000
    }

    // 创建多个波形圆环
    val waveCount = 3
    Box(
        modifier = modifier,
        contentAlignment = Alignment.Center
    ) {
        repeat(waveCount) { index ->
            val scale by infiniteTransition.animateFloat(
                initialValue = 0.3f,
                targetValue = 1f,
                animationSpec = infiniteRepeatable(
                    animation = tween(
                        durationMillis = animationDuration,
                        easing = LinearEasing
                    ),
                    repeatMode = RepeatMode.Restart,
                    initialStartOffset = StartOffset(index * (animationDuration / waveCount))
                )
            )

            val alpha by infiniteTransition.animateFloat(
                initialValue = 0.6f,
                targetValue = 0f,
                animationSpec = infiniteRepeatable(
                    animation = tween(
                        durationMillis = animationDuration,
                        easing = LinearEasing
                    ),
                    repeatMode = RepeatMode.Restart,
                    initialStartOffset = StartOffset(index * (animationDuration / waveCount))
                )
            )

            val waveColor = when (state) {
                AssistantState.CONNECTING -> Color(0xFFFF9800)
                AssistantState.LISTENING -> Color(0xFF4CAF50)
                AssistantState.THINKING -> Color(0xFFFFC107)
                AssistantState.SPEAKING -> Color(0xFF2196F3)
                else -> Color(0xFF6C757D)
            }

            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .scale(scale)
                    .background(
                        color = waveColor.copy(alpha = alpha * 0.3f),
                        shape = CircleShape
                    )
            )
        }
    }
}

@Composable
private fun MicrophoneButton(
    state: AssistantState,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val scale by animateFloatAsState(
        targetValue = if (state != AssistantState.IDLE) 1.1f else 1f,
        animationSpec = spring(
            dampingRatio = Spring.DampingRatioMediumBouncy,
            stiffness = Spring.StiffnessLow
        )
    )
    
    // 连接状态的旋转动画
    val infiniteTransition = rememberInfiniteTransition()
    val rotation by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(1000, easing = LinearEasing),
            repeatMode = RepeatMode.Restart
        )
    )

    val buttonColor = when (state) {
        AssistantState.IDLE -> Color(0xFF6C757D)
        AssistantState.CONNECTING -> Color(0xFFFF9800)
        AssistantState.LISTENING -> Color(0xFF4CAF50)
        AssistantState.THINKING -> Color(0xFFFFC107)
        AssistantState.SPEAKING -> Color(0xFF2196F3)
    }
    
    FloatingActionButton(
        onClick = onClick,
        modifier = modifier.scale(scale),
        containerColor = buttonColor,
        elevation = FloatingActionButtonDefaults.elevation(
            defaultElevation = 8.dp,
            pressedElevation = 12.dp
        )
    ) {
        val icon = when (state) {
            AssistantState.IDLE -> Icons.Filled.Mic
            AssistantState.CONNECTING -> Icons.Filled.Sync
            AssistantState.LISTENING -> Icons.Filled.GraphicEq
            AssistantState.THINKING -> Icons.Filled.Psychology
            AssistantState.SPEAKING -> Icons.Filled.RecordVoiceOver
        }
        
        Icon(
            imageVector = icon,
            contentDescription = when (state) {
                AssistantState.IDLE -> "点击开始"
                AssistantState.CONNECTING -> "连接中"
                AssistantState.LISTENING -> "录音中"
                AssistantState.THINKING -> "思考中"
                AssistantState.SPEAKING -> "播放中"
            },
            tint = Color.White,
            modifier = Modifier
                .size(36.dp)
                .then(
                    if (state == AssistantState.CONNECTING) {
                        Modifier.graphicsLayer { rotationZ = rotation }
                    } else {
                        Modifier
                    }
                )
        )
    }
}
